/* Copyright (C) 2011 Fredrique Samuels, fredriquesamuels@gmail.com 

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
 
#ifndef TRI_HEIGHTFIELD_H__
#define TRI_HEIGHTFIELD_H__


#include <base/vector.h>
#include <base/matrix.h>
#include <entity.h>


#include <stdlib.h>

#include <base/logging.h>
namespace tri{

class THeightField :public tri::TEntity{
private:
	
	unsigned short* m_HeightData;
	int m_Width;
	int m_Height;
	float m_Elevation;
	float m_ElevationInv;
	float CellSize;
	
public:
	THeightField() :  tri::TEntity(), m_HeightData(NULL), m_Width(0), m_Height(0), m_Elevation(1), m_ElevationInv(1/m_Elevation), CellSize(3.0){}
	virtual ~THeightField(){
		clear();
	}
	
	virtual void display(){
		for (int i=0;i<m_Height-1;i++){
			for (int j=0;j<m_Width-1;j++){
				glColor3f((float)i/m_Height,(float)i/m_Height,(float)i/m_Height);
				glBegin(GL_QUADS);
				glTexCoord2f(1.0f, 1.0f); glVertex3f((i)*CellSize,  m_HeightData[i*m_Width + (j+1)]*m_ElevationInv, (j+1)*CellSize);
				glTexCoord2f(1.0f, 0.0f); glVertex3f((i+1)*CellSize,  m_HeightData[(i+1)*m_Width + (j+1)]*m_ElevationInv, (j+1)*CellSize);
				glTexCoord2f(0.0f, 0.0f); glVertex3f((i+1)*CellSize,  m_HeightData[(i+1)*m_Width + j]*m_ElevationInv, j*CellSize);
				glTexCoord2f(0.0f, 1.0f); glVertex3f(i*CellSize,  m_HeightData[i*m_Width + j]*m_ElevationInv, j*CellSize);
				glEnd();
			}
		}
	}
	
	void setElevation(float e){
		m_Elevation = e;
		m_ElevationInv = 1/m_Elevation;
	}
	
	void clear(){
		if (m_HeightData!=NULL){
			delete m_HeightData;
			m_HeightData = NULL;
		}
		m_Width = 0;
		m_Height = 0;
	}
	
	void loadFromImage(std::string file){
		m_Width = 10;
		m_Height = 10;
		m_HeightData = new unsigned short[10*10];
		for (int i=0;i<m_Height;i++){
			for (int j=0;j<m_Width;j++){
				m_HeightData[i*m_Width + j] = j%2*1;
			}
		}
//		if(tri::sys::isFile(file)){
//			
//			TImageData image;
//			if ( loadImage(&image, file) ){
//				clear();
//				for (int)
//			}else{
//				tri::LOG_SEVERE( "Unable to load heightmap image : " + file );
//				tri::utils::quit();
//			}
//		}else{
//			tri::LOG_SEVERE( "Unable to locate heightmap image : " + file );
//			tri::utils::quit();
//		}
	}
};

}

#endif
